/* eslint-disable no-debugger */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import downLoad from "@/utils/download";
import {
	AppstoreOutlined,
	DeleteOutlined,
	DownloadOutlined,
	ExclamationCircleFilled,
	InfoCircleOutlined,
	MenuOutlined,
	PlusOutlined,
	ShareAltOutlined,
	TableOutlined
} from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns, ProTable } from "@ant-design/pro-components";
import {
	Button,
	Divider,
	Image,
	FormInstance,
	Input,
	Modal,
	Tabs,
	Space,
	Typography,
	message,
	TabsProps,
	Card,
	Flex,
	Radio,
	Row,
	Col
} from "antd";
import React, { useEffect, useRef, useState } from "react";
import CardList from "./components/CardList";
import uno from "@/assets/uno.svg";
import wps from "@/assets/wps.svg";
import FileDetails from "./components/FileDetilas";
import UploadForm from "./components/UploadForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, upload } from "@/services/api/module/tenant/storage/file";
import FilterDrawer from "@/components/FilterDrawer";
import { createTableColumns, pagination } from "./constants";
import styles from "./style/index.module.less";
import defaultSourceImg from "@/assets/source.png";
import { dict } from "@/utils/DictionaryCacheManager";
const { confirm } = Modal;
const OssFileList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [detailOpen, setDetailOpen] = useState<boolean>(false);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [dataSource, setDataSource] = useState<any>([]);
	const [fileTypeOptions, setFileTypeOptions] = useState<any>([]);
	const [showTab, setShowTab] = useState<string>("table");
	useEffect(() => {
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		dict.getDict("sys_file_type").then(data => {
			console.log(data);
			setFileTypeOptions(data);
		});
	}, []);
	// 列定义
	const handleColumnRemove = (record: API.Setting.StorageFileVo) => {
		handleRemove(record?.id);
	};
	const handleColumnDownload = (record: API.Setting.StorageFileVo) => {
		handleDownload(record?.id);
	};
	const handleColumnDetails = (record: API.Setting.StorageFileVo) => {
		setDataSource(record);
		setCurrentId(record?.id);
		setDetailOpen(true);
	};
	const columns = createTableColumns(fileTypeOptions, handleColumnRemove, handleColumnDownload, handleColumnDetails);
	// 删除
	const handleRemove = async (ids: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: any, names: any) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确定删除文件名称为：${names} 的文件吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};
	// 上传文件
	const handleUploadFile = async (params: Array<any>) => {
		let submitParams = [];
		const formData = new FormData();
		// @ts-ignore
		for (let i = 0; i < params?.files?.length; i++) {
			// @ts-ignore
			submitParams.push(params?.files[i]?.originFileObj);
		}
		// 逐个附加到 FormData 中
		for (let file of submitParams) {
			formData.append("files", file);
		}
		return new Promise((resolve, reject) => {
			upload(formData as any)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};

	const handleDownload = (ossId: number) => {
		downLoad.oss(ossId);
	};
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	const [data, setData] = useState<any>([]);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue }).then((data: any) => {
			setData(data?.data);
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			originalName: value
		});
		actionRef.current?.reload();
	};
	return (
		<>
			<Row gutter={[10, 10]}>
				<Col span={24}>
					<Card styles={{ body: { padding: "15px 25px" } }}>
						<Flex justify="space-between" align="center">
							<Space>
								<Button
									type="primary"
									onClick={() => {
										setFormOpen(true);
									}}
								>
									上传文件
								</Button>
								<Button
									type="primary"
									ghost
									disabled={selectedRows.length <= 0 || selectedRows.length > 1 ? true : false}
									onClick={() => {
										handleColumnDetails(selectedRows[0]);
									}}
								>
									预览
								</Button>
								<Button icon={<DownloadOutlined />} type="primary" ghost disabled={selectedRows.length > 0 ? false : true}>
									下载
								</Button>
								<Button type="primary" ghost icon={<ShareAltOutlined />}>
									分享
								</Button>
								{selectedRows.length > 0 && (
									<Button
										type="primary"
										danger
										onClick={() => {
											showRemoveConfirm(
												Array.from(selectedRows, ({ id }) => id),
												Array.from(selectedRows, ({ originalName }) => originalName)
											);
										}}
									>
										批量刪除
									</Button>
								)}
							</Space>
							<Space>
								<Input.Search placeholder="配置键" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
								<Radio.Group value={showTab} onChange={e => setShowTab(e.target.value)}>
									<Radio.Button value="table">
										<MenuOutlined />
									</Radio.Button>
									<Radio.Button value="list">
										<AppstoreOutlined />
									</Radio.Button>
								</Radio.Group>
							</Space>
						</Flex>
					</Card>
				</Col>
				<Col span={24}>
					<Card>
						{showTab === "table" && (
							<CustomerTable<API.Setting.StorageFileVo>
								actionRef={actionRef}
								tableAlertRender={false}
								tableStyle={{ minHeight: "calc(100vh - 280px)" }}
								formRef={formTableRef}
								rowKey="id"
								toolBarRender={false}
								search={false}
								pagination={pagination}
								request={tableDataRequest}
								columns={columns}
								rowSelection={{
									onChange: (_, selectedRows) => {
										setSelectedRows(selectedRows);
									}
								}}
							/>
						)}
						{showTab == "list" && (
							<Row gutter={[20, 30]}>
								{data.map(
									(item: {
										fileType: string;
										url: string | undefined;
										originalName: string;
										id: React.Key | null | undefined;
									}) => {
										return (
											<Col key={item.id} md={6} xl={4} xxl={4} lg={4} sm={6} xs={12}>
												<Space size={2} direction="vertical" align="center" className={styles.filePreviewList}>
													<div
														style={{
															width: "100%",
															marginBottom: 4,
															height: 100,
															borderRadius: 6,
															display: "flex",
															alignItems: "center",
															justifyContent: "center"
														}}
													>
														{item?.fileType == "img" && (
															<Image data-src={defaultSourceImg} loading="lazy" width={80} src={item?.url} />
														)}
														{item?.fileType == "doc" && <Image data-src={defaultSourceImg} loading="lazy" width={80} src={wps} />}
														{item?.fileType === null && (
															<Image
																data-src={defaultSourceImg}
																loading="lazy"
																preview={false}
																width={80}
																src={defaultSourceImg}
															/>
														)}
													</div>
													<Typography.Text ellipsis style={{ width: 100, textAlign: "center" }}>
														{item?.originalName}
													</Typography.Text>
												</Space>
											</Col>
										);
									}
								)}
							</Row>
						)}
					</Card>
				</Col>
			</Row>

			<UploadForm
				open={formOpen}
				onCancel={() => {
					setFormOpen(false);
				}}
				onSubmit={async (files: Array<any>) => {
					return handleUploadFile(files);
				}}
			/>
			<FileDetails
				open={detailOpen}
				id={currentId}
				fileType={fileTypeOptions}
				dataSource={dataSource}
				onCancel={() => {
					setDetailOpen(false);
					setDataSource(undefined);
					setCurrentId(undefined);
				}}
			/>
		</>
	);
};

export default OssFileList;
